import { _decorator, Component, Node, director , ToggleComponent,WebView} from 'cc';
import { WXSDK } from './extends/wx/WXSDK';
import { BridgeManager } from './BridgeManager';
import { UserApi } from './api/user';
import { UserModel } from './models/user';
import { Toast } from './utils/Toast';
import { ENV } from './config/main';
const { ccclass, property } = _decorator;

@ccclass('Login')
export class Login extends Component {
    @property(Node)
    private loginBtn: Node = null;

    @property(Node)
    private privateText: Node = null;
    // 用户协议
    @property(Node)
    private agreementText: Node = null;

    @property(Node)
    private agreementLayer: Node = null;

    @property(Node)
    private agreementLayerClose: Node = null;

    @property(Node)
    private privacyPage: Node = null;

    @property(ToggleComponent)
    private toggle: ToggleComponent = null;

    @property(Toast)
    toast: Toast = null;

    private privateUrl: string = "https://ad.jvlihd.cn/privacy.html";
    private agreementUrl: string = "https://ad.jvlihd.cn/agreemen.html";


    start() {
        // 避免重复注册事件监听器
        this.loginBtn.off(Node.EventType.TOUCH_START); // 先移除之前可能存在的监听器
        this.loginBtn.on(Node.EventType.TOUCH_START, this.wxLogin, this);
        
        this.agreementText.off(Node.EventType.TOUCH_START);
        this.privateText.off(Node.EventType.TOUCH_START);
        this.agreementLayerClose.off(Node.EventType.TOUCH_START);
        
        this.agreementText.on(Node.EventType.TOUCH_START, this.openAgreement, this);
        this.privateText.on(Node.EventType.TOUCH_START, this.openPrivate, this);
        this.agreementLayerClose.on(Node.EventType.TOUCH_START, this.closeAgreement, this);



        if(ENV.IS_PASS_LOGIN){
            this.loginSuccess();
            return;
        }


        // 检查是否已登录
        const isLoggedIn = UserModel.getInstance().isLoggedIn();
        if (isLoggedIn) {
            this.loginSuccess();
            return;
        }

        // 显示温馨提示
        this.privacyPage.active = true;

        // 注册微信登录回调 - 确保只注册一次
        if (!BridgeManager.getInstance().hasCallback("onWXLogin")) {
            BridgeManager.getInstance().registerCallback("onWXLogin", (code) => {
                this.loginWithCode(code);
                console.log("onWXLogin", code);
            });
        }

        const code = UserModel.getInstance().getUserCode();
        if(code && code !== ""){
            this.loginWithCode(code);
        }
    }

    public openPrivate(){
        const webView = this.agreementLayer.getChildByName("WebView")?.getComponent(WebView);
        if(webView){
            webView.url = this.privateUrl;
        }
        this.agreementLayer.active = true;
    }

    public openAgreement(){
        const webView = this.agreementLayer.getChildByName("WebView")?.getComponent(WebView);
        if(webView){
            webView.url = this.agreementUrl;
        }
        this.agreementLayer.active = true;
    }

    private closeAgreement(){
        this.agreementLayer.active = false;
    }

  

    /**
     * 使用code登录
     * @param code 微信登录code
     */
    private async loginWithCode(code: string) {
        try {
            // 调用登录接口
            const data = await UserApi.login({ code });
            console.log("loginWithCode", JSON.stringify(data));
            
            // 保存用户数据
            UserModel.getInstance().setUserInfo(data);
            // 保存code
            UserModel.getInstance().setUserCode(code);
            // 登录成功
            this.loginSuccess();
        } catch (error) {
            console.error('登录失败:', error);
        }
    }

    /**
     * 登录成功后的处理
     */
    private loginSuccess() {
        console.log("登录成功，跳转到主场景");
        director.loadScene('scene');
    }



    /**
     * 微信登录
     */
    private async wxLogin() {

        if(!this.toggle.isChecked){
            this.toast.show("请同意用户协议和隐私政策");
            return;
        }

        if(CC_DEBUG){
            this.loginSuccess();
            return;
        }

        try {
            await WXSDK.getInstance().login();
        } catch (error) {
            console.error('微信登录失败:', error);
        }
    }

    /**
     * 分享到微信
     */
    shareToWeChat() {
        WXSDK.getInstance().share(
            '煎饼果子传奇',
            '煎饼果子传奇描述',
            'https://ad.jvlihd.cn/',
            0  // 分享到会话
        );
    }
}


